package com.gaogzhen.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaogzhen.domain.User;
import com.gaogzhen.dto.UserDto;
import com.gaogzhen.feigh.UserServiceFeign;
import com.gaogzhen.mappers.UserDtoMapper;
import com.gaogzhen.model.*;
import com.gaogzhen.service.UserService;
import com.gaogzhen.utils.CurrentUser;
import com.gaogzhen.utils.R;
import com.gaogzhen.vo.UserAuthInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 * @description 会员管理控制器
 * @date 2022-06-08 10:14
 */
@RestController
@RequestMapping("/users")
@Api(tags = "会员管理控制器")
public class UserController implements UserServiceFeign {

    @Autowired
    private UserService userService;

    @GetMapping
    @ApiOperation("分页查询会员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小"),
            @ApiImplicitParam(name = "userId", value = "会员id"),
            @ApiImplicitParam(name = "userName", value = "会员名"),
            @ApiImplicitParam(name = "realName", value = "会员姓名"),
            @ApiImplicitParam(name = "mobile", value = "手机号"),
            @ApiImplicitParam(name = "status", value = "状态"),
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<Page<User>> findByPage(@ApiIgnore Page<User> page, String userId, String userName, String realName, String mobile, Integer status) {
        return R.ok(userService.findByPage(page, userId, userName, realName, mobile, status, null));

    }

    @GetMapping("/info")
    @ApiOperation("查询会员详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "会员id")
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<User> info(Long id) {
        return R.ok(userService.getById(id));

    }

    @PatchMapping
    @ApiOperation("更新会员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "会员信息")
    })
    @PreAuthorize("hasAuthority('user_update')")
    public R update(@RequestBody @Validated User user) {
        userService.updateUser(user);
        return R.ok();
    }

    @PatchMapping("/status")
    @ApiOperation("启用禁用会员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "会员id"),
            @ApiImplicitParam(name = "status", value = "启用禁用状态"),
    })
    @PreAuthorize("hasAuthority('user_update')")
    public R updateStatus(String id, Integer status) {
        userService.updateStatus(id, status);
        return R.ok();
    }

    @GetMapping("/directInvites")
    @ApiOperation("分页查询会员邀请列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小"),
            @ApiImplicitParam(name = "userId", value = "会员id"),
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<Page<User>> getDirectInvites(@ApiIgnore Page<User> page, Long userId) {
        return R.ok(userService.getDirectInvites(page, userId));

    }

    @GetMapping("/auths")
    @ApiOperation("分页查询会员审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小"),
            @ApiImplicitParam(name = "userId", value = "会员id"),
            @ApiImplicitParam(name = "userName", value = "会员名"),
            @ApiImplicitParam(name = "realName", value = "会员姓名"),
            @ApiImplicitParam(name = "mobile", value = "手机号"),
            @ApiImplicitParam(name = "reviewsStatus", value = "会员状态")
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<Page<User>> findUserAuths(@ApiIgnore Page<User> page, String userId, String userName, String realName, String mobile, Integer reviewsStatus) {
        return R.ok(userService.findByPage(page, userId, userName, realName, mobile, null, reviewsStatus));

    }

    @GetMapping("/auth/info")
    @ApiOperation("查询会员认证审核详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "会员id")
    })
    @PreAuthorize("hasAuthority('user_query')")
    public R<UserAuthInfoVo> getAuthInfo(Long id) {
        return R.ok(userService.getAuthInfo(id));

    }

    /**
     * 审核：
     *  对于一组图片（唯一标识code）的认可，符合条件，审核通过
     */
    @PostMapping("/auths/status")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的id"),
            @ApiImplicitParam(name = "authStatus", value = "审核状态"),
            @ApiImplicitParam(name = "authCode", value = "一组图片唯一标识"),
            @ApiImplicitParam(name = "remark", value = "拒绝原因"),
    })
    public R updateUserAuthStatus(@RequestParam(required = true) Long id, @RequestParam(required = true) Integer authStatus, @RequestParam(required = true) Long authCode, @RequestParam(required = false) String remark) {
        userService.updateUserAuthStatus(id, authStatus, authCode, remark);
        return R.ok();
    }

    @GetMapping("/current/info")
    @ApiOperation(value = "获取当前登录用户信息")
    public R<User> currentUserInfo() {
        Long userId = CurrentUser.getCurrentUserId();
        User user = userService.getById(userId);
        // 屏蔽重要信息：密码，密钥
        user.setPassword("******");
        user.setPaypassword("******");
        user.setAccessKeyId("******");
        user.setAccessKeySecret("******");

        return R.ok(user);
    }

    @PostMapping("/authAccount")
    @ApiOperation(value = "用户实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userAuthForm", value = "用户实名认证信息"),
    })
    public R identifyCheck(@RequestBody UserAuthForm userAuthForm) {
        Long currentUserId = CurrentUser.getCurrentUserId();
        boolean isOk = userService.identifyVerify(currentUserId, userAuthForm);
        return isOk? R.ok(): R.fail("认证失败");
    }

    @PostMapping("/authUser")
    @ApiOperation(value = "用户高级实名认证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "images", value = "认证照片"),
    })
    public R authUser(@RequestBody String[] images) {
        userService.authUser(CurrentUser.getCurrentUserId(), Arrays.asList(images));
        return R.ok();
    }

    @PostMapping("/updatePhone")
    @ApiOperation(value = "修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updatePhoneParam", value = "updatePhoneParam 的json数据")
    })
    public R updatePhone(@RequestBody @Validated UpdatePhoneParam updatePhoneParam) {
        userService.updatePhone(CurrentUser.getCurrentUserId(), updatePhoneParam);
        return R.ok();
    }

    @GetMapping("/checkTel")
    @ApiOperation(value = "检查手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号"),
            @ApiImplicitParam(name = "countryCode", value = "国家code")
    })
    public R checkTel(@RequestParam(required = true) String mobile, @RequestParam(required = true) String countryCode) {
        userService.checkTel(mobile, countryCode);
        return R.ok();
    }

    @PostMapping("/updateLoginPassword")
    @ApiOperation(value = "修改登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updateLoginPasswordParam", value = "updateLoginPasswordParam 的json数据")
    })
    public R updateLoginPassword(@RequestBody @Validated UpdatePasswordParam updatePassword) {
        userService.updateLoginPassword(CurrentUser.getCurrentUserId(), updatePassword);
        return R.ok();
    }

    @PostMapping("/updatePayPassword")
    @ApiOperation(value = "修改交易密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updateLoginPasswordParam", value = "updateLoginPasswordParam 的json数据")
    })
    public R updatePayPassword(@RequestBody @Validated UpdatePasswordParam updatePassword) {
        userService.updatePayPassword(CurrentUser.getCurrentUserId(), updatePassword);
        return R.ok();
    }

    @PostMapping("/setPayPassword")
    @ApiOperation(value = "重新设置交易密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resetPayPasswordParam", value = "resetPayPasswordParam 的json数据")
    })
    public R resetPayPassword(@RequestBody @Validated ResetPayPasswordParam resetPayPasswordParam) {
        userService.resetPayPassword(CurrentUser.getCurrentUserId(), resetPayPasswordParam);
        return R.ok();
    }

    @GetMapping("/invites")
    @ApiOperation(value = "查询当前用户的邀请列表")
    public R<List<User>> getUserInvites() {
        List<User> users = userService.getUserInvites(CurrentUser.getCurrentUserId());
        return R.ok(users);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resetPayPasswordParam", value = "resetPayPasswordParam 的json数据")
    })
    public R register(@RequestBody @Validated RegisterParam registerParam) {
        userService.register(registerParam);
        return R.ok();
    }

    @PostMapping("/setPassword")
    @ApiOperation(value = "重置登录密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resetPasswordParam", value = "resetPasswordParam 的json数据")
    })
    public R resetPassword(@RequestBody @Validated ResetPasswordParam resetPasswordParam) {
        userService.resetPassword(resetPasswordParam);
        return R.ok();
    }

    /**
     * 远程调用
     *  通过用户id批量查询用户的简要信息
     * @return
     */
    @Override
    public Map<Long, UserDto> getBriefUsers(List<Long> ids, String username, String mobile) {
        return userService.getBriefUsers(ids, username, mobile);
    }

    @Override
    public UserDto getUserById(Long id) {
        User user = userService.getById(id);
        return UserDtoMapper.INSTANCE.convert2Dto(user);
    }

}
